using System.Net.Http.Headers;
using System.Text;

namespace BootstrapBlazorApp.Server.LLMs.model.TongYi;

public static class TongYiUtils
{
    public static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
    {
        HttpClient httpClient = new HttpClient();
        using var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
        // 设置请求头
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        using HttpResponseMessage response = await httpClient.PostAsync(url, content);
        try
        {
            // 发送请求并获取响应
            response.EnsureSuccessStatusCode();
        }
        catch
        {
            await using var Stream = await response.Content.ReadAsStreamAsync();
            using var read = new StreamReader(Stream);
            Console.WriteLine(await read.ReadToEndAsync());
        }


        await using var responseStream = await response.Content.ReadAsStreamAsync();
        using var reader = new StreamReader(responseStream);
        return await reader.ReadToEndAsync();
    }

    public static async IAsyncEnumerable<string?> SendPostRequestStreamAsync(string url, string jsonContent,
        string apiKey)
    {
        HttpClient httpClient = new HttpClient();
        using var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
        // 设置请求头
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
        httpClient.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");


        // 发送请求并获取响应
        using HttpResponseMessage response = await httpClient.PostAsync(url, content);
        try
        {
            response.EnsureSuccessStatusCode();
        }
        catch (Exception e)
        {
            await using var responseStreams = await response.Content.ReadAsStreamAsync();
            using var readers = new StreamReader(responseStreams);
            Console.WriteLine(e.Message);
            Console.WriteLine(await readers.ReadToEndAsync());
        }


        await using var responseStream = await response.Content.ReadAsStreamAsync();
        using var reader = new StreamReader(responseStream);
        while (await reader.ReadLineAsync() is { } line)
        {
            if (string.IsNullOrWhiteSpace(line))
            {
                continue;
            }

            yield return Parse(line);

            await Task.Delay(100);
        }
        
       
    }
    //处理SSE
    
    private static string? Parse(string text)
    {
        var lines = text.Split(["\r\n", "\r", "\n"], StringSplitOptions.None);

        return (from line in lines where line.StartsWith("data:") select line[5..]).FirstOrDefault();
    }
    
}

